//
//  NSString+composed.m
//  togetherLBS
//
//  Created by Phyllis Hu on 13-4-17.
//  Copyright (c) 2013年 celi. All rights reserved.
//

#import "NSString+composed.h"
#import "NSDate+MJ.h"

@implementation NSString (composed)

- (NSString *)URLEncodedString:(NSString *)escaped
{
    NSString *result = (NSString *)CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault,(CFStringRef)self,NULL,(CFStringRef)escaped,kCFStringEncodingUTF8));
    return result;
}

- (NSString *)URLDecodedString
{
    //NSString *result = (NSString *)CFBridgingRelease(CFURLCreateStringByPercentEscapes(kCFAllocatorDefault,(CFStringRef)self,NULL,(CFStringRef)unescaped,kCFStringEncodingUTF8));
    NSString *result = [self stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    return result;
}

-(BOOL)isComposedOfNumbers
{
    NSCharacterSet *disallowedCharacters = [[NSCharacterSet decimalDigitCharacterSet] invertedSet];
    
    NSRange foundRange = [self rangeOfCharacterFromSet:disallowedCharacters];
    if (foundRange.location != NSNotFound) {
        return NO;
    }
    return YES;
}

-(BOOL)isComposedOfNumbersAndLetters
{
    NSCharacterSet *disallowedCharacters = [[NSCharacterSet characterSetWithCharactersInString:@"0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"] invertedSet];
    NSRange foundRange = [self rangeOfCharacterFromSet:disallowedCharacters];
    if (foundRange.location != NSNotFound) {
        return NO;
    }
    return YES;
}

- (BOOL)containCharacterInString:(NSString *)nStr
{
    NSCharacterSet *theCharacters = [NSCharacterSet characterSetWithCharactersInString:nStr];
    NSRange foundRange = [self rangeOfCharacterFromSet:theCharacters];
    if (foundRange.location == NSNotFound) {
        return NO;
    }
    return YES;
}


- (BOOL)isValidPassword
{
    if (self.length < 4 || self.length > 16) {
        return NO;
    }
    NSCharacterSet *disallowedCharacters = [[NSCharacterSet characterSetWithCharactersInString:@"0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_"] invertedSet];
    NSRange foundRange = [self rangeOfCharacterFromSet:disallowedCharacters];
    if (foundRange.location != NSNotFound) {
        return NO;
    }
    return YES;
}
- (NSString *)stringUsedForName
{
    NSCharacterSet *unableSet = [NSCharacterSet characterSetWithCharactersInString:@"-&{}\":,;，｛｝："];
    NSString *name = [self stringByReplacingAllCharaterInSet:unableSet byString:@" "];
    
    return  [name stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
}

- (NSString *)stringByReplacingAllCharaterInSet:(NSCharacterSet *)sSet byString:(NSString *)nStr
{
    NSMutableString *desStr = [[NSMutableString alloc] initWithString:self];
    
    NSRange foudRange = [desStr rangeOfCharacterFromSet:sSet];
    while (foudRange.location != NSNotFound) {
        [desStr replaceCharactersInRange:foudRange withString:nStr];
        foudRange = [desStr rangeOfCharacterFromSet:sSet];
    }
    return desStr;
}

- (BOOL)isSixNumPassword
{
    if (self.length != 6) {
        return NO;
    }
    return [self isComposedOfNumbers];
}

- (BOOL)isValidPhone
{
    if (self.length <3 || self.length > 16) {
        return NO;
    }
    char c = [self characterAtIndex:0];
    if (self.length == 1 && c == '0') {
        return NO;
    }
    NSString *subStr = nil;
    if (c == '+') {
        subStr = [self substringFromIndex:1];
        
    }else{
        subStr = self;
    }
    return [subStr isComposedOfNumbers];
}

/**
 *  判断是否是合法的邮箱地址
 */
-(BOOL)isValidEmail
{
    BOOL stricterFilter = YES; // Discussion http://blog.logichigh.com/2010/09/02/validating-an-e-mail-address/
    //NSString *stricterFilterString = @"[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}";
    NSString *stricterFilterString = @"^\\w+([-+.]\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*$";
    NSString *laxString = @".+@.+\\.[A-Za-z]{2}[A-Za-z]*";
    NSString *emailRegex = stricterFilter ? stricterFilterString : laxString;
    NSPredicate *emailTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", emailRegex];
    return [emailTest evaluateWithObject:self];
}

-(NSInteger)lineswithLimit:(NSInteger)num
{
    NSInteger lines = 0;
    NSArray *subStrs = [self componentsSeparatedByString:@"\n"];
    for (NSString *temp in subStrs)
    {
        lines += (temp.length + num -1)/num;//向上取整
    }
    return lines;
}

-(CGFloat)heightNeededWithFixedWidth:(CGFloat)width andFont:(UIFont *)font
{
    CGFloat heith = 0;
    NSArray *subStrs = [self componentsSeparatedByString:@"\n"];
    for (NSString *temp in subStrs)
    {
        //CGSize size = [temp sizeWithFont:font forWidth:width lineBreakMode:NSLineBreakByWordWrapping];
        CGSize size = [temp sizeWithMyFont:font constrainedToSize:CGSizeMake(width, 10000) lineBreakMode:CLLineBreakByWordWrapping];
        heith += size.height;
    }
    return heith;
}

#pragma mark - sizeOfFont
//用于单行显示的
- (CGSize)sizeWithMyFont:(UIFont *)font
{
    if ([self respondsToSelector:@selector(sizeWithAttributes:)])
    {
        NSDictionary* attribs = @{NSFontAttributeName:font};
        return ([self sizeWithAttributes:attribs]);
    }
    return ([self sizeWithFont:font]);
}

//用于单行显示
- (CGSize)sizeWithMyFont:(UIFont *)font forWidth:(CGFloat)width lineBreakMode:(NSLineBreakMode)lineBreakMode
{
    if ([self respondsToSelector:@selector(boundingRectWithSize:options:attributes:context:)])
    {
        NSDictionary* attribs = @{NSFontAttributeName:font,NSParagraphStyleAttributeName:[NSParagraphStyle defaultParagraphStyle]};
        CGSize size = CGSizeMake(width, 9999);
        return ([self boundingRectWithSize:size options:NSStringDrawingUsesLineFragmentOrigin attributes:attribs context:Nil].size);
    }
    return ([self sizeWithFont:font forWidth:width lineBreakMode:lineBreakMode]);
}
//多行显示
- (CGSize)sizeWithMyFont:(UIFont *)font constrainedToSize:(CGSize)size
{
    if ([self respondsToSelector:@selector(boundingRectWithSize:options:attributes:context:)])
    {
        NSDictionary* attribs = @{NSFontAttributeName:font};
        return ([self boundingRectWithSize:size options:NSStringDrawingUsesLineFragmentOrigin attributes:attribs context:Nil].size);
    }
    return ([self sizeWithFont:font constrainedToSize:size]);
}
//多行显示
- (CGSize)sizeWithMyFont:(UIFont *)font constrainedToSize:(CGSize)size lineBreakMode:(NSLineBreakMode)lineBreakMode
{
    if ([self respondsToSelector:@selector(boundingRectWithSize:options:attributes:context:)])
    {
        NSDictionary* attribs = @{NSFontAttributeName:font,NSParagraphStyleAttributeName:[NSParagraphStyle defaultParagraphStyle]};
        return ([self boundingRectWithSize:size options:NSStringDrawingUsesLineFragmentOrigin attributes:attribs context:Nil].size);
    }
    return ([self sizeWithFont:font constrainedToSize:size lineBreakMode:lineBreakMode]);
}

// 根据数字的二进制位判断星期几
+ (NSString *)stringWithSchedule:(NSInteger)schedule
{
    if (schedule == 0) {
        return CLLocalizedString(@"NoRepeat", nil);
    } else if (schedule == 127) {
        return CLLocalizedString(@"EveryDay", nil);
    } else {
        NSMutableString *desc = [NSMutableString string];
        for (int i = 0; i < 7; i++) {
            int num = (schedule >> i) & 1;
            if (num == 1) {
                NSString *str = [NSString stringWithFormat:@"WeekDay%d",i+1];
                NSString *locStr = CLLocalizedString(str, nil);
                [desc appendString:locStr];
                [desc appendString:@","];
            }
        }
        [desc deleteCharactersInRange:NSMakeRange(desc.length-1, 1)];
        return desc;
    }
}

// 0900 转成 09:00
+ (NSString *)stringForTimeFormat:(NSString *)time
{
//    yyyy-MM-dd HH:mm:ss
    NSString *str1 = [time substringToIndex:2];
    NSString *str2 = [time substringFromIndex:2];
    return [NSString stringWithFormat:@"%@:%@", str1, str2];
}

// 09:00装成0900
+ (NSString *)stringFromTimeString:(NSString *)timeStr
{
    NSArray *array = [timeStr componentsSeparatedByString:@":"];
    return [NSString stringWithFormat:@"%@%@", array[0], array[1]];
}

+ (NSString *)stringWithErrorCode:(NSInteger)errorCode
{
    NSString *errorName = [NSString stringWithFormat:@"error%ld", (long)errorCode];
    NSString *errorMsg = CLLocalizedString(errorName, nil);
    return errorMsg;
}

+ (NSString *)stringWithNetworkStatus:(NSInteger)status
{
    NSString *netStatus = nil;
    switch (status) {
        case 0:
            netStatus = @"NoNetWork";
            break;
        case 1:
            netStatus = @"2G/3G";
            break;
        case 2:
            netStatus = @"wifi";
            break;
        default:
            break;
    }
    return netStatus;
}

+ (NSString *)stringWithModeType:(NSInteger)modeType
{
    NSString *name = nil;
    switch (modeType) {
        case 0:
            name = CLLocalizedString(@"SecureMode", nil);
            break;
        case 1:
            name = CLLocalizedString(@"QuietMode", nil);
            break;
        case 2:
            name = CLLocalizedString(@"GuardianMode", nil);
            break;
        case 3:
            name = CLLocalizedString(@"TrackMode", nil);
            break;
        case 4:
            name = CLLocalizedString(@"AirplaneMode", nil);
            break;
        case 5:
            name = CLLocalizedString(@"CustomMode", nil);
            break;
        case 6:
            name = CLLocalizedString(@"SchoolGuardian", nil);
            break;
        case 7:
            name = CLLocalizedString(@"ClassDisable", nil);
            break;
        default:
            break;
    }
    return name;
}

+ (NSString *)stringWithHalfHourAfter:(NSString *)timeStr
{
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"HH:mm"];
    NSDate *date = [formatter dateFromString:timeStr];
    NSDate *halfHourDate = date.halfHourAfter;

    return [formatter stringFromDate:halfHourDate];
}
@end
